package com.jinzhi.jzweb.service.impl.draw;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jinzhi.common.base.CoreServiceImpl;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.dao.BookPurchaseDao;
import com.jinzhi.jzweb.dao.StuSignUpComDao;
import com.jinzhi.jzweb.dao.StuSignUpDao;
import com.jinzhi.jzweb.dao.TrackDrawDao;
import com.jinzhi.jzweb.domain.BookPurchaseDO;
import com.jinzhi.jzweb.domain.StuSignUpComDO;
import com.jinzhi.jzweb.domain.TrackDrawDO;
import com.jinzhi.jzweb.service.BookPurchaseService;
import com.jinzhi.jzweb.service.StuSignUpService;
import com.jinzhi.jzweb.service.draw.FuZhouDrawService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: mcf
 * @CreateTime: 2024/10/31
 * @Description: 福州文教赛道抽签
 *
 * -------------------抽签规则----------------------
 * 32个学校，66个选手（有一个学校两支队伍）
 * 抽签结果显示
 * 1选手比赛B赛道
 * 2选手去对应C赛道
 * B赛道1～16上午比赛，17到33下午比赛（上午比完封闭不出考场）
 * C赛道1～16上午比赛，17到33下午比赛（同样封闭等待）
 *
 */
@Service
public class FuZhouDrawServiceImpl extends CoreServiceImpl<TrackDrawDao, TrackDrawDO> implements FuZhouDrawService {

    @Autowired
    private StuSignUpComDao stuSignUpComDao;

    /**
     * 抽签
     * @return
     */
    @Override
    public Result<?> draw() {
        //查询选手信息
        List<StuSignUpComDO> signList = stuSignUpComDao.selectList(new EntityWrapper<StuSignUpComDO>().orderBy("id", true));
        if(signList==null || signList.isEmpty()) return Result.fail("暂无选手信息");
        //创建抽签序号
        List<String> numB = new ArrayList<>();
        List<String> numC = new ArrayList<>();
        for (int i = 0; i < signList.size()/2; i++) {
            numB.add(i+1+"");
            numC.add(i+1+"");
        }
        Random random = new Random();
        Collections.shuffle(numB, random); // 随机打乱赛道
        Collections.shuffle(numC, random); // 随机打乱赛道
        //存储最终的抽签结果
        List<TrackDrawDO> drawList = new LinkedList<>();
        // 打乱"stuSignUpComDOS"顺序
        Collections.shuffle(signList);
        int sort = 0;
        // 对同一院校的选手分组
        Map<String, List<StuSignUpComDO>> trackDrawByUnitMap = signList.stream()
                .collect(Collectors.groupingBy(StuSignUpComDO::getUnitName));

        for (Map.Entry<String, List<StuSignUpComDO>> entry : trackDrawByUnitMap.entrySet()){
            TrackDrawDO trackDrawDO = new TrackDrawDO();
            trackDrawDO.setUnitName(entry.getValue().get(0).getUnitName());//学校名称
            trackDrawDO.setName(entry.getValue().get(0).getName());//选手1
            trackDrawDO.setPlaceNum(numB.get(0));//序号1
            numB.remove(numB.get(0));
            trackDrawDO.setPlaceNum2(numC.get(0));//序号2
            numC.remove(numC.get(0));
            trackDrawDO.setName2(entry.getValue().get(1).getName());//选手2
            //赛道
            int num = random.nextInt(2);
            if(num==0){
                trackDrawDO.setTrack("B");trackDrawDO.setTrack2("C");
            }else{
                trackDrawDO.setTrack("C");trackDrawDO.setTrack2("B");
            }
            trackDrawDO.setSort(sort+=1);
            drawList.add(trackDrawDO);
        }
        //清空之前的抽签记录
        this.delete(new EntityWrapper<TrackDrawDO>());
        if(null!=drawList && !drawList.isEmpty()){
            this.insertBatch(drawList);
        }
        return Result.ok(drawList);
    }

    /**
     * 查询上一次抽签结果
     * @return
     */
    @Override
    public TrackDrawDO trackList() {
        TrackDrawDO resultVO = new TrackDrawDO();
        resultVO.setHasDraw(true);//默认为true.不存在上次抽签结果时改为false
        //查询上一次的抽签结果
        Wrapper<TrackDrawDO> wrapper = new EntityWrapper<>();
        wrapper.orderBy("sort",true);
        List<TrackDrawDO> trackDrawDOS = this.selectList(wrapper);
        //如果没有抽签上一次抽签结果那就默认初始化
        if(trackDrawDOS==null || trackDrawDOS.size()==0){
            resultVO.setHasDraw(false);
            List<StuSignUpComDO> stuSignUpComDOS = stuSignUpComDao.selectList(new EntityWrapper<StuSignUpComDO>().orderBy("id",true));
            if(stuSignUpComDOS!=null && stuSignUpComDOS.size()>0){
                // 对同一院校的选手分组
                Map<String, List<StuSignUpComDO>> trackDrawByUnitMap = stuSignUpComDOS.stream()
                        .collect(Collectors.groupingBy(StuSignUpComDO::getUnitName));
                for (String s : trackDrawByUnitMap.keySet()) {
                    TrackDrawDO trackDrawDO = new TrackDrawDO();
                    trackDrawDO.setUnitName(s);
                    for (int i = 0; i < trackDrawByUnitMap.get(s).size(); i++) {
                        String name = trackDrawByUnitMap.get(s).get(i).getName();
                        if (i==0){
                            trackDrawDO.setName(name);
                        } else if (i==1) {
                            trackDrawDO.setName2(name);
                        }else {
                            break;
                        }
                    }
                    trackDrawDOS.add(trackDrawDO);
                }
            }
        }
        resultVO.setTrackDrawDOList(trackDrawDOS);

        return resultVO;
    }

    /**
     * 参赛学校抽签
     * @return
     */
    @Override
    public Result<?> schoolDraw() {
        List<StuSignUpComDO> signList = stuSignUpComDao.selectList(new EntityWrapper<StuSignUpComDO>().orderBy("id", true));
        if(signList==null || signList.isEmpty()) return Result.fail("暂无选手信息");

        // 对同一院校的选手分组
        Map<String, List<StuSignUpComDO>> trackDrawByUnitMap = signList.stream()
                .collect(Collectors.groupingBy(StuSignUpComDO::getUnitName));

        int schoolCount = trackDrawByUnitMap.size();

        // 平等分配：每组基础数量
        int baseSize = schoolCount / 3;
        int remainder = schoolCount % 3; // 余数

        // 分配余数：多1个给A，多2个给A和B各1个
        int groupASize = baseSize + (remainder >= 1 ? 1 : 0);
        int groupBSize = baseSize + (remainder >= 2 ? 1 : 0);
        int groupCSize = baseSize;

        // 生成A、B、C三组的序号列表
        List<String> groupAList = new ArrayList<>();
        List<String> groupBList = new ArrayList<>();
        List<String> groupCList = new ArrayList<>();

        for (int i = 1; i <= groupASize; i++) {
            groupAList.add("A" + i);
        }
        for (int i = 1; i <= groupBSize; i++) {
            groupBList.add("B" + i);
        }
        for (int i = 1; i <= groupCSize; i++) {
            groupCList.add("C" + i);
        }

        // 合并所有序号（按A、B、C顺序）
        List<String> allNumList = new ArrayList<>();
        allNumList.addAll(groupAList);
        allNumList.addAll(groupBList);
        allNumList.addAll(groupCList);

        Random random = new Random();

        // 先复制一份用于随机分配
        List<String> randomNumList = new ArrayList<>(allNumList);
        Collections.shuffle(randomNumList, random);

        List<TrackDrawDO> drawDOS = new LinkedList<>();
        int sortOrder = 0;

        // 为每个学校分配抽签序号
        for (String schoolName : trackDrawByUnitMap.keySet()) {
            TrackDrawDO trackDrawDO = new TrackDrawDO();
            trackDrawDO.setUnitName(schoolName);
            trackDrawDO.setRecordNumber(randomNumList.get(0));
            randomNumList.remove(0);

            // 根据分配的序号在原始有序列表中的位置设置sort
            String recordNumber = trackDrawDO.getRecordNumber();
            int indexInOrderedList = allNumList.indexOf(recordNumber);
            trackDrawDO.setSort(indexInOrderedList + 1); // 从1开始排序

            drawDOS.add(trackDrawDO);
        }

        this.delete(new EntityWrapper<TrackDrawDO>());
        if(!drawDOS.isEmpty()){
            this.insertBatch(drawDOS);
        }
        return Result.ok(drawDOS);
    }

    @Override
    public TrackDrawDO trackSchoolList() {
        TrackDrawDO resultVO = new TrackDrawDO();
        resultVO.setHasDraw(true);//默认为true.不存在上次抽签结果时改为false
        //查询上一次的抽签结果
        Wrapper<TrackDrawDO> wrapper = new EntityWrapper<>();
//        wrapper.orderBy("sort",true);
        List<TrackDrawDO> trackDrawDOS = this.selectList(wrapper);
        //如果没有抽签上一次抽签结果那就默认初始化
        if(trackDrawDOS==null || trackDrawDOS.size()==0){
            resultVO.setHasDraw(false);
            List<StuSignUpComDO> stuSignUpComDOS = stuSignUpComDao.selectList(new EntityWrapper<StuSignUpComDO>().orderBy("id",true));
            if(stuSignUpComDOS!=null && stuSignUpComDOS.size()>0){
                // 对同一院校的选手分组
                Map<String, List<StuSignUpComDO>> trackDrawByUnitMap = stuSignUpComDOS.stream()
                        .collect(Collectors.groupingBy(StuSignUpComDO::getUnitName));
                for (String s : trackDrawByUnitMap.keySet()) {
                    TrackDrawDO trackDrawDO = new TrackDrawDO();
                    trackDrawDO.setUnitName(s);
                    for (int i = 0; i < trackDrawByUnitMap.get(s).size(); i++) {
                        String name = trackDrawByUnitMap.get(s).get(i).getName();
                        if (i==0){
                            trackDrawDO.setName(name);
                        } else if (i==1) {
                            trackDrawDO.setName2(name);
                        }else {
                            break;
                        }
                    }
                    trackDrawDOS.add(trackDrawDO);
                }
            }
        }
        resultVO.setTrackDrawDOList(trackDrawDOS);

        return resultVO;
    }


}
